const { body, query, validationResult } = require('express-validator');
const { pool } = require('../config/db');
const { code } = require('three/tsl');
const { upload } = require('../util/uploadConfig');

//基本校验...
const questionParamsValidation=[

  query('page')
    .optional()
    .isInt({min:1})
    .withMessage('页码必须是大于等于1的整数!')
    .toInt(),
  
  query('limit')
    .optional()
    .isInt({min:10,max:50})
    .withMessage('每页数据必须是大于等于10且小于等于50的整数!')
    .toInt(),

  query('sort')
    .optional()
    .isIn(['created','view_count'])
    .withMessage('查询规则不正确!'),

  query('order')
    .optional()
    .isIn(['DESC','ASC'])
    .withMessage('排序方式不正确!')
]

// 获取所有问题
exports.getAllQuestions = [...questionParamsValidation,async (req, res, next) => {
  try {
    const { page = 1, limit = 10, sort = 'created', order = 'DESC' } = req.query;
    const offset = (page - 1) * limit;
    

    // 获取问题列表
    const [questions] = await pool.query(
      `SELECT q.*, u.username, u.avatar, c.name as category_name 
       FROM questions q
       JOIN users u ON q.user_id = u.id
       JOIN questioncata c ON q.category_id = c.id
       ORDER BY ${sort} ${order}
       LIMIT ? OFFSET ?`,
      [limit, offset]
    );

    // 获取总数量
    const [countResult] = await pool.query('SELECT COUNT(*) as total FROM questions');
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: questions.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: questions
    });
  } catch (err) {
    next(err);
  }
}];

//获取所有的简化版问题
exports.getAllQuestionsSimplify = [...questionParamsValidation,upload,async (req,res,next) =>{
  try{
    const { page=1, limit=30, sort='created',order='DESC' } = req.query;
    const offset =(page-1)*limit;

    const [questions]= await pool.query(`
      SELECT questions.id, questions.title, users.username, questions.view_count, questions.answer_count, questions.is_solved, questioncata.questionname, questions.created
      FROM questions
      JOIN users ON questions.user_id=users.id
      JOIN questioncata ON questions.category_id = questioncata.id
      ORDER BY questions.${sort} ${order}
      LIMIT ${limit} OFFSET ${offset} 
      `)
    
    const [questionCount] = await pool.query(`SELECT COUNT(*) as total FROM questions`);
    const total = parseInt(questionCount[0].total)

    res.status(200).json({
      code:200,
      msg:'问题预览获取失败',
      data:questions,
      currentPage:page,
      count:total,
      totalPages: Math.ceil(total / limit),
    })

  }catch(err){
      next(err);
  }
}];

// 根据ID获取问题
exports.getQuestionById = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 获取问题详情
    const [questions] = await pool.query(
      `SELECT questions.*,users.username,users.email,users.avatar,questioncata.questionname
        FROM questions
        JOIN users ON questions.user_id = users.id
        JOIN questioncata ON questions.category_id = questioncata.id
        WHERE questions.id = ?`,
      [id]
    );

    

    if (questions.length === 0) {
      const error = new Error('未找到该问题');
      error.statusCode = 404;
      throw error;
    }

    // 增加浏览量
    await pool.query('UPDATE questions SET view_count = view_count + 1 WHERE id = ?', [id]);

    res.status(200).json({
      code:200,
      msg:'获取问题详情失败',
      data: questions[0]
    });
  } catch (err) {
    next(err);
  }
};

// 创建问题
exports.createQuestion = async (req, res, next) => {
  try {
    const { title, content, category_id, user_id } = req.body;

    // 验证必填字段
    if (!title || !content || !category_id || !user_id) {
      const error = new Error('标题、内容、分类和用户ID为必填项');
      error.statusCode = 400;
      throw error;
    }

    // 检查分类是否存在
    const [categories] = await pool.query('SELECT id FROM questioncata WHERE id = ?', [category_id]);
    if (categories.length === 0) {
      const error = new Error('指定的分类不存在');
      error.statusCode = 400;
      throw error;
    }

    // 检查用户是否存在
    const [users] = await pool.query('SELECT id FROM users WHERE id = ?', [user_id]);
    if (users.length === 0) {
      const error = new Error('指定的用户不存在');
      error.statusCode = 400;
      throw error;
    }

    // 创建问题
    const [result] = await pool.query(
      `INSERT INTO questions 
       (title, content, category_id, user_id, views, created_at, updated_at) 
       VALUES (?, ?, ?, ?, 0, NOW(), NOW())`,
      [title, content, category_id, user_id]
    );

    // 获取新创建的问题
    const [newQuestion] = await pool.query(
      `SELECT q.*, u.username, u.avatar, c.name as category_name 
       FROM questions q
       JOIN users u ON q.user_id = u.id
       JOIN questioncata c ON q.category_id = c.id
       WHERE q.id = ?`,
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      message: '问题创建成功',
      data: newQuestion[0]
    });
  } catch (err) {
    next(err);
  }
};

// 更新问题
exports.updateQuestion = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { title, content, category_id, user_id } = req.body;

    // 检查问题是否存在
    const [questions] = await pool.query('SELECT * FROM questions WHERE id = ?', [id]);
    if (questions.length === 0) {
      const error = new Error('未找到该问题');
      error.statusCode = 404;
      throw error;
    }

    // 检查权限 - 只有问题创建者可以更新
    if (questions[0].user_id !== parseInt(user_id)) {
      const error = new Error('没有权限更新此问题');
      error.statusCode = 403;
      throw error;
    }

    // 构建更新字段
    const updateFields = [];
    const values = [];

    if (title) {
      updateFields.push('title = ?');
      values.push(title);
    }

    if (content) {
      updateFields.push('content = ?');
      values.push(content);
    }

    if (category_id) {
      // 检查分类是否存在
      const [categories] = await pool.query('SELECT id FROM questioncata WHERE id = ?', [category_id]);
      if (categories.length === 0) {
        const error = new Error('指定的分类不存在');
        error.statusCode = 400;
        throw error;
      }
      updateFields.push('category_id = ?');
      values.push(category_id);
    }

    updateFields.push('updated_at = NOW()');
    values.push(id);

    if (updateFields.length <= 1) { // 只添加了updated_at
      const error = new Error('没有提供需要更新的字段');
      error.statusCode = 400;
      throw error;
    }

    // 执行更新
    await pool.query(
      `UPDATE questions SET ${updateFields.join(', ')} WHERE id = ?`,
      values
    );

    // 获取更新后的问题
    const [updatedQuestion] = await pool.query(
      `SELECT q.*, u.username, u.avatar, c.name as category_name 
       FROM questions q
       JOIN users u ON q.user_id = u.id
       JOIN questioncata c ON q.category_id = c.id
       WHERE q.id = ?`,
      [id]
    );

    res.status(200).json({
      success: true,
      message: '问题更新成功',
      data: updatedQuestion[0]
    });
  } catch (err) {
    next(err);
  }
};

// 删除问题
exports.deleteQuestion = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { user_id } = req.body;

    // 检查问题是否存在
    const [questions] = await pool.query('SELECT * FROM questions WHERE id = ?', [id]);
    if (questions.length === 0) {
      const error = new Error('未找到该问题');
      error.statusCode = 404;
      throw error;
    }

    // 检查权限 - 只有问题创建者可以删除
    if (questions[0].user_id !== parseInt(user_id)) {
      const error = new Error('没有权限删除此问题');
      error.statusCode = 403;
      throw error;
    }

    // 执行删除
    await pool.query('DELETE FROM questions WHERE id = ?', [id]);

    res.status(200).json({
      success: true,
      message: '问题删除成功',
      data: {}
    });
  } catch (err) {
    next(err);
  }
};

// 根据分类获取问题
exports.getQuestionsByCategory = async (req, res, next) => {
  try {
    const { categoryId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    // 检查分类是否存在
    const [categories] = await pool.query('SELECT id FROM questioncata WHERE id = ?', [categoryId]);
    if (categories.length === 0) {
      const error = new Error('指定的分类不存在');
      error.statusCode = 404;
      throw error;
    }

    // 获取问题列表
    const [questions] = await pool.query(
      `SELECT q.*, u.username, u.avatar, c.name as category_name 
       FROM questions q
       JOIN users u ON q.user_id = u.id
       JOIN questioncata c ON q.category_id = c.id
       WHERE q.category_id = ?
       ORDER BY q.created_at DESC
       LIMIT ? OFFSET ?`,
      [categoryId, parseInt(limit), parseInt(offset)]
    );

    // 获取总数量
    const [countResult] = await pool.query(
      'SELECT COUNT(*) as total FROM questions WHERE category_id = ?',
      [categoryId]
    );
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: questions.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: questions
    });
  } catch (err) {
    next(err);
  }
};

// 根据用户获取问题
exports.getQuestionsByUser = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    // 检查用户是否存在
    const [users] = await pool.query('SELECT id FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      const error = new Error('指定的用户不存在');
      error.statusCode = 404;
      throw error;
    }

    // 获取问题列表
    const [questions] = await pool.query(
      `SELECT q.*, u.username, u.avatar, c.name as category_name 
       FROM questions q
       JOIN users u ON q.user_id = u.id
       JOIN questioncata c ON q.category_id = c.id
       WHERE q.user_id = ?
       ORDER BY q.created_at DESC
       LIMIT ? OFFSET ?`,
      [userId, parseInt(limit), parseInt(offset)]
    );

    // 获取总数量
    const [countResult] = await pool.query(
      'SELECT COUNT(*) as total FROM questions WHERE user_id = ?',
      [userId]
    );
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: questions.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: questions
    });
  } catch (err) {
    next(err);
  }
};
